import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  // 购物车数组
  carts = [];
  addCart (pro) {
    if (this.carts.length === 0) {
      const obj = {
        img: pro.img,
        title: pro.title,
        gui: pro.gui,
        num: pro.num,
        price: pro.price,
        total: pro.total
      };
      this.carts.push(obj);
    } else {
      // 购物车里有数据了
      const isHas = this.carts.some((value) => {
        return value.title === pro.title;
      });
      if (isHas) {
        // 购物车已经有该对象了
        const arr = this.carts.filter((value) => {
          return value.title === pro.title;
        });
        let obj = arr[0];
        obj.num = pro.num;
      } else {
        // 购物车没有该对象
        const obj = {
          img: pro.img,
          title: pro.title,
          gui: pro.gui,
          num: pro.num,
          price: pro.price,
          total: pro.total
        };
        this.carts.push(obj);
      }
    }
  }
  // 删除购物车中的商品
  deDeletion (e) {
    this.carts.splice(this.carts.indexOf(e), 1);
  }
  // 获取商品的总个数
  getToalCount () {
    let sum = 0;
    for (let i = 0; i < this.carts.length; i++) {
      sum += this.carts[i].num;
    }
    return sum;
  }
  // 获取商品总价
  getTotalPrice () {
    let sum = 0;
    for (let i = 0; i < this.carts.length; i++) {
      sum += this.carts[i].total;
    }
    return sum;
  }
  // 点击加号
  doClickJ (e) {
    e.num++;
  }
  // 点击减号
  doClickH (e) {
    if (e.num > 1) {
      e.num--;
    } else if (e.num === 1) {
      e.num = 1;
    }
  }
}
